package edu.ccut.saturn.studio.core.search.dialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.dialogs.AbstractElementListSelectionDialog;

import edu.ccut.saturn.studio.Activator;
import edu.ccut.saturn.studio.Images;
import edu.ccut.saturn.studio.core.search.IObserver;
import edu.ccut.saturn.studio.core.search.SaturnFileSearcher;
import edu.ccut.saturn.studio.core.search.SaturnFileSearcher.SearchResult;
import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnSWTUtils;
import edu.ccut.saturn.studio.naviagtor.SaturnFile;

public class TwoCompontentSearchDialog extends
		AbstractElementListSelectionDialog {


	private List<SearchResult> jspresultInWorkspace = new ArrayList<SearchResult>();
	private List<SearchResult> actionresultInWorkspace = new ArrayList<SearchResult>();
	private List<SearchResult> allresultInWorkspace = new ArrayList<SearchResult>();
	String [] suffixes = new String[2];

	
	public TwoCompontentSearchDialog(Shell parent, String [] suffixes) {
		super(parent, new SaturnSWTUtils.SaturnLabelDefaultProvider() {
			
			@Override
			public Image getImage(Object element) {
				if (element instanceof SearchResult) {
					SearchResult result = (SearchResult) element;

					String fileName = result.getFileName();
					int index = fileName.lastIndexOf(".");  //$NON-NLS-1$

					if (index >= 0 && index < fileName.length()) {
						String suffix = fileName.substring(index + 1);

						return SaturnFile.getImageFromFileType(suffix);
					}
				}
				return super.getImage(element);
			}
		});
		this.suffixes = suffixes;
	}

	public TwoCompontentSearchDialog(Shell parent, ILabelProvider renderer) {
		super(parent, renderer);
	}

	protected Point getInitialSize() {
		return new Point(600, 500);
	}

	protected void computeResult() {
		setResult(Arrays.asList(getSelectedElements()));
	}

	protected Control createDialogArea(Composite parent) {
		getShell().setText(Messages.getString("TwoCompontentSearchDialog.2"));  //$NON-NLS-1$
		Composite contents = (Composite) super.createDialogArea(parent);
		createSearch(contents);
		createFilterText(contents);
		createFilteredList(contents);
		createMessageArea(contents);
		setListElements(new String[] { "" });  //$NON-NLS-1$
		setSelection(getInitialElementSelections().toArray());

		return contents;
	}

	protected Text createJarPathText(Composite parent) {

		Text text = new Text(parent, SWT.BORDER | SWT.READ_ONLY);

		GridData data = new GridData();
		data.grabExcessVerticalSpace = false;
		data.grabExcessHorizontalSpace = true;
		data.horizontalAlignment = GridData.FILL;
		data.verticalAlignment = GridData.BEGINNING;
		text.setLayoutData(data);
		text.setFont(parent.getFont());

		return text;
	}

	private Composite createSearch(Composite parent) {

		final Composite composite = new Composite(parent, SWT.NONE);
		final GridData gd_composite = new GridData(SWT.FILL, SWT.FILL, true,
				false);
		gd_composite.heightHint = 28;
		composite.setLayoutData(gd_composite);
		composite.setLayout(new FormLayout());

		final Label label = new Label(composite, SWT.NONE);
		final FormData fd_label = new FormData();
		fd_label.bottom = new FormAttachment(0, 24);
		fd_label.top = new FormAttachment(16);
		fd_label.right = new FormAttachment(0, 27);
		fd_label.left = new FormAttachment(0, 2);
		label.setLayoutData(fd_label);
		label.setText("Key");  //$NON-NLS-1$

		final ToolBar toolBar = new ToolBar(composite, SWT.FLAT);
		final FormData fd_toolBar = new FormData();
		fd_toolBar.top = new FormAttachment(0);
		fd_toolBar.right = new FormAttachment(100);
		toolBar.setLayoutData(fd_toolBar);
		final ToolItem allToolItem = new ToolItem(toolBar, SWT.DROP_DOWN);
		allToolItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (e.detail == 0) {
					if (allresultInWorkspace.isEmpty()) {
						startThreadProject();
					}
					setListElements(allresultInWorkspace.toArray());
				}
			}
		});

		allToolItem.setImage(Activator.getImage(Images.AMPLIFY_PLUS));
		final Menu menu = new Menu(toolBar);
		addDropDown(allToolItem, menu);
		
		
		MenuItem JspMenuItem = new MenuItem(menu, SWT.NONE);
		JspMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				setListElements(jspresultInWorkspace.toArray());
			}
		});
		JspMenuItem.setText(Messages.getString("TwoCompontentSearchDialog.search") + suffixes[1]);    //$NON-NLS-1$
		
		
		MenuItem ActionMenuItem = new MenuItem(menu, SWT.NONE);
		ActionMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				setListElements(actionresultInWorkspace.toArray());
			}
		});
		ActionMenuItem.setText(Messages.getString("TwoCompontentSearchDialog.search2") + suffixes[0]);    //$NON-NLS-1$
		
		
		MenuItem AllMenuItem = new MenuItem(menu, SWT.NONE);
		AllMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {

				setListElements(allresultInWorkspace.toArray());
			}
		});
		AllMenuItem.setText(Messages.getString("TwoCompontentSearchDialog.5"));   //$NON-NLS-1$
		startThreadProject();
		return composite;
	}

	private static void addDropDown(final ToolItem item, final Menu menu) {
		item.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				if (event.detail == SWT.ARROW) {
					Rectangle rect = item.getBounds();
					Point pt = new Point(rect.x, rect.y + rect.height);
					pt = item.getParent().toDisplay(pt);
					menu.setLocation(pt.x, pt.y);
					menu.setVisible(true);
				}
			}
		});
	}

	protected void startThreadProject() {
		new Thread(new Runnable() {
			public void run() {
//				String [] suffixes = {"jsp", "action"};    //$NON-NLS-1$ //$NON-NLS-2$
				try {
					SaturnFileSearcher.getValueAndDocumentMapInWorkspace(suffixes, (new IObserver() {
							public synchronized void update(final List<SearchResult> files) {
								Display.getDefault().asyncExec(new Runnable() {
									public void run() {
										allresultInWorkspace = files;
										setDifferetSuffixList(allresultInWorkspace);
										setListElements(files.toArray());
									}
								});
							}
						}), null);
					
				} catch (Exception e) {
					e.printStackTrace();
				}		
			}
		}).start();
	}

	
	private void setDifferetSuffixList(List<SearchResult> allresultInWorkspace) {
		int suffixIngdex ;
		String resultFileName ; 
		String resultFilesuffix;
		for (SearchResult searchResult: allresultInWorkspace) {
			resultFileName = searchResult.getFileName();
			suffixIngdex = resultFileName.indexOf(".");  //$NON-NLS-1$
			resultFilesuffix = resultFileName.substring(suffixIngdex + 1, resultFileName.length());
			
			if (resultFilesuffix.equalsIgnoreCase(suffixes[0])) {  
				actionresultInWorkspace.add(searchResult);
			}
			if (resultFilesuffix.equalsIgnoreCase(suffixes[1])) {  
				jspresultInWorkspace.add(searchResult);
			}
		}
	}
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setImage(Activator.getImage(Images.SATURN_ICONS_SMALLNAME));
	}
}
